using AutoMapper;
using lwzlz.Application.System.Dto;
using lwzlz.Core;
using lwzlz.Core.Repository;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Common;
using System.Linq;

namespace lwzlz.Application.System
{
    public class OrderService
    {
        private readonly IRepository<Order> _repository;
        private readonly IRepository<OrderRecord> _orderRecordRepository;
        private readonly IRepository<OrderDetail> _orderDetailRepository;

        public OrderService()
        {
            _repository = new Repository<Order>();
            _orderRecordRepository = new Repository<OrderRecord>();
            _orderDetailRepository = new Repository<OrderDetail>();
        }

        #region 查询

        /// <summary>
        /// 获取实体
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public Order Get(int id)
        {
            return _repository.Get(id);
        }

        /// <summary>
        /// 获取输出对象
        /// </summary>
        /// <typeparam name="TDto"></typeparam>
        /// <param name="id"></param>
        /// <returns></returns>
        public TDto Get<TDto>(int id) where TDto : class, new()
        {
            var entity = Get(id);
            return Mapper.Map<TDto>(entity);
        }

        /// <summary>
        /// 分页数据
        /// </summary>
        /// <param name="dic_conditions"></param>
        /// <param name="count"></param>
        /// <returns></returns>
        public List<dynamic> GetListPage(
            int pageNumber, int rowsPerPage, Dictionary<string, string> dic_conditions, string field, string order, out int count)
        {
            #region 字段
            var select = @"
                t1.*,
                t2.UserName AS MemberUserName,
                t2.RealName AS MemberRealName";
            #endregion

            #region 表
            var table = @"
                    dbo.Ser_Order t1
                LEFT JOIN dbo.Ser_Member t2
                    ON t2.Id = t1.MemberId";
            #endregion

            #region 参数查询

            string where = " 0=0 ";

            //数据库参数
            Dictionary<string, object> dic = new Dictionary<string, object>();

            //用户名
            if (dic_conditions.ContainsKey("MemberUserName"))
            {
                dic.Add("@MemberUserName", dic_conditions["MemberUserName"]);
                where += " AND t2.UserName=@MemberUserName ";
            }
            //商品Id
            if (dic_conditions.ContainsKey("MemberRealName"))
            {
                dic.Add("@MemberRealName", dic_conditions["MemberRealName"]);
                where += " AND t2.RealName=@MemberRealName ";
            }
            //订单编号
            if (dic_conditions.ContainsKey("OrderCode"))
            {
                dic.Add("@Code", dic_conditions["OrderCode"]);
                where += " AND t1.Code=@Code ";
            }
            //状态（1-未消费；2-交易成功;3-退单）
            if (dic_conditions.ContainsKey("Status"))
            {
                dic.Add("@Status", dic_conditions["Status"]);
                where += " AND t1.Status=@Status ";
            }

            #endregion

            #region 排序

            //排序sql语句拼接
            string orderby = " t1.CreationTime DESC ";//默认排序
            if (!string.IsNullOrWhiteSpace(field))
            {
                orderby = string.Format("{0} {1}", field, string.IsNullOrWhiteSpace(order) ? "DESC" : order);
            }

            #endregion

            var sql = $"SELECT {select} FROM {table} WHERE {where} ";

            var list = _repository.GetDynamicPaged(pageNumber, rowsPerPage, orderby, sql, dic).ToList();

            count = _repository.RecordQueryCount(sql, dic);

            return list;
        }

        /// <summary>
        /// 获取查询结果行数
        /// </summary>
        /// <param name="conditions"></param>
        /// <param name="param"></param>
        /// <returns></returns>
        public int GetListCount(string conditions, object param)
        {
            return _repository.RecordCount(conditions, param);
        }

        /// <summary>
        /// 获取前端展示
        /// </summary>
        /// <param name="pageNumber"></param>
        /// <param name="rowsPerPage"></param>
        /// <param name="count"></param>
        /// <returns></returns>
        public List<MemberOrder> GetList(int pageNumber, int rowsPerPage, int memberId, string keyword, out int count)
        {
            var list = new List<MemberOrder>();
            var dic = new Dictionary<string, object>();
            string where = " WHERE IsDeleted = 0 ";
            //会员ID
            {
                where += " AND MemberId = @MemberId";
                dic.Add("MemberId", memberId);
            }
            //关键词
            if (!string.IsNullOrWhiteSpace(keyword))
            {
                where += " AND Code = @Code";
                dic.Add("Code", keyword);
            }
            string orderby = " OrderTime DESC";

            var orderList = _repository.GetListPaged(pageNumber, rowsPerPage, where, orderby, dic).ToList();
            count = _repository.RecordCount(where, dic);
            var orderIds = orderList.Select(p => p.Id).ToList();
            var orderDetailList = _orderDetailRepository.GetList("WHERE OrderId IN @OrderId", new { OrderId = orderIds }).ToList();
            foreach (var order in orderList)
            {
                var memberOrder = new MemberOrder()
                {
                    Id = order.Id,
                    Code = order.Code,
                    Status = order.Status,
                    OrderTime = order.OrderTime,
                    TotalAmount = order.TotalAmount,
                    LogisticsCompany = order.LogisticsCompany,
                    LogisticsNumber = order.LogisticsNumber,
                    Details = new List<MemberOrderDetail>()
                };
                var detailList = orderDetailList.Where(p => p.OrderId == order.Id).ToList();
                foreach (var detail in detailList)
                {
                    var memberOrderDetail = new MemberOrderDetail()
                    {
                        CommodityId = detail.CommodityId,
                        CommodityName = detail.CommodityName,
                        CategoryName = detail.CategoryName,
                        CommodityPic = detail.CommodityPic,
                        CommodityMoney = detail.CommodityMoney,
                        Number = detail.Number,
                        TotalMoney = detail.TotalMoney
                    };
                    memberOrder.Details.Add(memberOrderDetail);
                }
                list.Add(memberOrder);
            }

            return list;
        }

        #endregion

        #region 编辑
        /// <summary>
        /// 添加
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public int? Insert(Order entity, DbTransaction dbtran)
        {
            return _repository.Insert(entity, dbtran);
        }

        /// <summary>
        /// 添加
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public int Add(OrderInput model)
        {
            var dbtran = _repository.BeginTransaction();//开启事务
            try
            {
                var entity = Mapper.Map<Order>(model);
                entity.CreatorUserId = UserAuthentication.GetCurrentUser().UserID;
                entity.CreationTime = DateTime.Now;

                int? Id = _repository.Insert(entity, dbtran);

                dbtran.Commit();//提交事务
                return 1;
            }
            catch (Exception ee)
            {
                dbtran.Rollback();//事务回滚
                throw new Exception(ee.Message);
            }
            finally
            {
                dbtran.Dispose();//释放事务资源
            }
        }

        /// <summary>
        /// 修改
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public int? Update(Order entity, IDbTransaction dbtran)
        {
            return _repository.Update(entity, dbtran);
        }

        /// <summary>
        /// 修改
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public int Edit(OrderInput model)
        {
            var dbtran = _repository.BeginTransaction();//开启事务
            try
            {
                DateTime now = DateTime.Now;

                var entity = _repository.Get(model.Id, dbtran);
                Mapper.Map(model, entity);//把model数据转移到entity
                entity.LastModifierUserId = UserAuthentication.GetCurrentUser().UserID;
                entity.LastModificationTime = DateTime.Now;

                _repository.Update(entity, dbtran);
                dbtran.Commit();//提交事务
                return 1;
            }
            catch (Exception ee)
            {
                dbtran.Rollback();//事务回滚
                throw new Exception(ee.Message);
            }
            finally
            {
                dbtran.Dispose();//释放事务资源
            }
        }

        /// <summary>
        /// 批量删除
        /// </summary>
        /// <param name="IdList"></param>
        /// <returns></returns>
        public void DeleteList(string IdList)
        {
            var dbtran = _repository.BeginTransaction();//开启事务
            try
            {
                foreach (string Id in IdList.Split(new Char[] { ',' }, StringSplitOptions.RemoveEmptyEntries))
                {
                    Order model = _repository.Get(Id, dbtran);
                    model.IsDeleted = true;
                    _repository.Update(model, dbtran);
                }
                dbtran.Commit();//提交事务
            }
            catch (Exception)
            {
                dbtran.Rollback();//事务回滚
            }
            finally
            {
                dbtran.Dispose();//释放事务资源
            }
        }

        /// <summary>
        /// 批量支付
        /// </summary>
        /// <param name="IdList"></param>
        /// <returns></returns>
        public void PaySuccessList(string IdList)
        {
            var dbtran = _repository.BeginTransaction();//开启事务
            try
            {
                foreach (string Id in IdList.Split(new Char[] { ',' }, StringSplitOptions.RemoveEmptyEntries))
                {
                    Order model = _repository.Get(Id, dbtran);
                    if (model != null)
                    {
                        if (model.Status == 10)
                        {
                            model.Status = 20;
                            _repository.Update(model, dbtran);

                            var record = new OrderRecord()
                            {
                                OrderId = model.Id,
                                Type = 20,
                                CreationTime = DateTime.Now,
                                CreatorUserId = UserAuthentication.GetCurrentUser()?.UserID
                            };
                            _orderRecordRepository.Insert(record, dbtran);
                        }
                        else
                        {
                            throw new Exception("订单状态错误");
                        }
                    }
                    else
                    {
                        throw new Exception("订单获取失败");
                    }
                }
                dbtran.Commit();//提交事务
            }
            catch (Exception ee)
            {
                dbtran.Rollback();//事务回滚
                throw new Exception(ee.Message);
            }
            finally
            {
                dbtran.Dispose();//释放事务资源
            }
        }

        /// <summary>
        /// 批量确认
        /// </summary>
        /// <param name="IdList"></param>
        /// <returns></returns>
        public void ConfirmPayList(string IdList)
        {
            var dbtran = _repository.BeginTransaction();//开启事务
            try
            {
                foreach (string Id in IdList.Split(new Char[] { ',' }, StringSplitOptions.RemoveEmptyEntries))
                {
                    Order model = _repository.Get(Id, dbtran);
                    if (model != null)
                    {
                        if (model.Status == 20)
                        {
                            model.Status = 30;
                            _repository.Update(model, dbtran);

                            var record = new OrderRecord()
                            {
                                OrderId = model.Id,
                                Type = 30,
                                CreationTime = DateTime.Now,
                                CreatorUserId = UserAuthentication.GetCurrentUser()?.UserID
                            };
                            _orderRecordRepository.Insert(record, dbtran);
                        }
                        else
                        {
                            throw new Exception("订单状态错误");
                        }
                    }
                    else
                    {
                        throw new Exception("订单获取失败");
                    }
                }
                dbtran.Commit();//提交事务
            }
            catch (Exception ee)
            {
                dbtran.Rollback();//事务回滚
                throw new Exception(ee.Message);
            }
            finally
            {
                dbtran.Dispose();//释放事务资源
            }
        }

        /// <summary>
        /// 批量取消
        /// </summary>
        /// <param name="IdList"></param>
        /// <returns></returns>
        public void CancelList(string IdList)
        {
            var dbtran = _repository.BeginTransaction();//开启事务
            try
            {
                foreach (string Id in IdList.Split(new Char[] { ',' }, StringSplitOptions.RemoveEmptyEntries))
                {
                    Order model = _repository.Get(Id, dbtran);
                    if (model != null)
                    {
                        if (model.Status != 90)
                        {
                            model.Status = 90;
                            _repository.Update(model, dbtran);

                            var record = new OrderRecord()
                            {
                                OrderId = model.Id,
                                Type = 50,
                                CreationTime = DateTime.Now,
                                CreatorUserId = UserAuthentication.GetCurrentUser()?.UserID
                            };
                            _orderRecordRepository.Insert(record, dbtran);
                        }
                        else
                        {
                            throw new Exception("订单状态错误");
                        }
                    }
                    else
                    {
                        throw new Exception("订单获取失败");
                    }
                }
                dbtran.Commit();//提交事务
            }
            catch (Exception ee)
            {
                dbtran.Rollback();//事务回滚
                throw new Exception(ee.Message);
            }
            finally
            {
                dbtran.Dispose();//释放事务资源
            }
        }

        /// <summary>
        /// 批量发货
        /// </summary>
        /// <param name="IdList"></param>
        /// <returns></returns>
        public void DeliverGoodsList(string IdList, string LogisticsCompany, string LogisticsNumber)
        {
            var dbtran = _repository.BeginTransaction();//开启事务
            try
            {
                foreach (string Id in IdList.Split(new Char[] { ',' }, StringSplitOptions.RemoveEmptyEntries))
                {
                    Order model = _repository.Get(Id, dbtran);
                    if (model != null)
                    {
                        if (model.Status == 30)
                        {
                            model.Status = 40;
                            model.LogisticsCompany = LogisticsCompany;
                            model.LogisticsNumber = LogisticsNumber;
                            _repository.Update(model, dbtran);

                            var record = new OrderRecord()
                            {
                                OrderId = model.Id,
                                Type = 40,
                                CreationTime = DateTime.Now,
                                CreatorUserId = UserAuthentication.GetCurrentUser()?.UserID
                            };
                            _orderRecordRepository.Insert(record, dbtran);
                        }
                        else
                        {
                            throw new Exception("订单状态错误");
                        }
                    }
                    else
                    {
                        throw new Exception("订单获取失败");
                    }
                }
                dbtran.Commit();//提交事务
            }
            catch (Exception ee)
            {
                dbtran.Rollback();//事务回滚
                throw new Exception(ee.Message);
            }
            finally
            {
                dbtran.Dispose();//释放事务资源
            }
        }

        #endregion
    }
}

